from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import PricingPlan, Subscription, Payment
from .serializers import (
    PricingPlanSerializer, SubscriptionSerializer, PaymentSerializer,
    SubscriptionCreateSerializer, PaymentCreateSerializer
)
from django.utils import timezone
from django.db.models import Q


class PricingPlanViewSet(viewsets.ModelViewSet):
    """
    价格方案视图集
    """
    queryset = PricingPlan.objects.filter(is_active=True)
    serializer_class = PricingPlanSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    
    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [permissions.IsAdminUser()]
        return [permissions.IsAuthenticatedOrReadOnly()]


class SubscriptionViewSet(viewsets.ModelViewSet):
    """
    订阅视图集
    """
    serializer_class = SubscriptionSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        user = self.request.user
        if user.is_staff:
            return Subscription.objects.all()
        return Subscription.objects.filter(user=user)
    
    def get_serializer_class(self):
        if self.action in ['create']:
            return SubscriptionCreateSerializer
        return SubscriptionSerializer
    
    @action(detail=False, methods=['get'])
    def current(self, request):
        """
        获取当前用户的活跃订阅
        """
        user = request.user
        try:
            subscription = Subscription.objects.get(
                user=user,
                status='active',
                end_date__gt=timezone.now()
            )
            serializer = self.get_serializer(subscription)
            return Response(serializer.data)
        except Subscription.DoesNotExist:
            return Response(
                {"detail": "没有找到活跃的订阅"},
                status=status.HTTP_404_NOT_FOUND
            )
    
    @action(detail=True, methods=['post'])
    def cancel_auto_renew(self, request, pk=None):
        """
        取消自动续订
        """
        subscription = self.get_object()
        if subscription.user != request.user and not request.user.is_staff:
            return Response(
                {"detail": "您没有权限执行此操作"},
                status=status.HTTP_403_FORBIDDEN
            )
        
        subscription.auto_renew = False
        subscription.save()
        
        return Response({"detail": "已成功取消自动续订"})


class PaymentViewSet(viewsets.ModelViewSet):
    """
    支付视图集
    """
    serializer_class = PaymentSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        user = self.request.user
        if user.is_staff:
            return Payment.objects.all()
        return Payment.objects.filter(user=user)
    
    def get_serializer_class(self):
        if self.action in ['create']:
            return PaymentCreateSerializer
        return PaymentSerializer
    
    @action(detail=True, methods=['post'])
    def process_payment(self, request, pk=None):
        """
        处理支付（模拟支付成功）
        """
        payment = self.get_object()
        
        # 检查权限
        if payment.user != request.user and not request.user.is_staff:
            return Response(
                {"detail": "您没有权限执行此操作"},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查支付状态
        if payment.status != 'pending':
            return Response(
                {"detail": f"支付已经是 {payment.status} 状态，无法处理"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 模拟支付处理
        payment.status = 'completed'
        payment.transaction_id = f"sim_{timezone.now().timestamp()}"
        payment.save()
        
        # 更新订阅状态
        subscription = payment.subscription
        subscription.is_active = True
        
        # 如果是续订，延长结束日期
        if subscription.end_date and subscription.end_date > timezone.now():
            subscription.end_date = subscription.end_date + timezone.timedelta(days=subscription.plan.duration_days)
        else:
            # 新订阅，设置开始和结束日期
            subscription.start_date = timezone.now()
            subscription.end_date = timezone.now() + timezone.timedelta(days=subscription.plan.duration_days)
        
        subscription.save()
        
        # 更新用户会员类型
        user = payment.user
        user.membership_type = subscription.plan.name
        user.save()
        
        return Response({
            "detail": "支付处理成功",
            "payment": PaymentSerializer(payment).data,
            "subscription": SubscriptionSerializer(subscription).data
        })
